package org.beian.fmmall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import org.beian.fmmall.VO.ResStatus;
import org.beian.fmmall.VO.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }
        String token = request.getHeader("token");
        if(token==null){
            doResponse(response,new ResultVO(ResStatus.LOGIN_FAIL_NOT,"请先登录！",null));
        }else{
            String s = stringRedisTemplate.boundValueOps(token).get();
            if(s==null){
                doResponse(response,new ResultVO(ResStatus.LOGIN_FAIL_NOT,"请先登录！",null));
            }else{
                stringRedisTemplate.boundValueOps(token).expire(1,TimeUnit.MINUTES);
                return true;
            }
//            try {
//                JwtParser parser = Jwts.parser();
//                parser.setSigningKey("beian");
//                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
//                return true;
//            } catch (ExpiredJwtException e) {
//                doResponse(response,new ResultVO(ResStatus.LOGIN_FAIL_OVERDUE,"登录过期，请重新登陆！",null));
//            } catch (UnsupportedJwtException e) {
//                doResponse(response,new ResultVO(ResStatus.LOGIN_FAIL_NOT,"Token不合法,请自重！",null));
//            } catch (Exception e) {
//                doResponse(response,new ResultVO(ResStatus.LOGIN_FAIL_NOT,"请先登录！",null));
//            }
        }
        return false;
    }
    public void doResponse(HttpServletResponse response,ResultVO resultVO) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVO);
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
